package org.newlucene.core.index;

import java.io.IOException;

import org.newlucene.core.document.Document;
import org.newlucene.core.store.Directory;
import org.newlucene.core.store.InputStream;

final class FieldDataReader
{
	private FieldInfos fieldInfos;
	private InputStream fieldsStream;
	private InputStream indexStream;
	private int size;

	FieldDataReader(Directory d, String segment, FieldInfos fn) throws IOException
	{
		fieldInfos = fn;

		fieldsStream = d.openFile(segment + ".fdt");
		indexStream = d.openFile(segment + ".fdx");

		size = (int)indexStream.length() / 8;
	}

	final void close() throws IOException
	{
		fieldsStream.close();
		indexStream.close();
	}

	final int size()
	{
		return size;
	}

	final Document doc(int n) throws IOException
	{
		indexStream.seek(n * 8L);
		long position = indexStream.readLong();
		fieldsStream.seek(position);
    
		Document doc = new Document();
		int numFields = fieldsStream.readVInt();
		for (int i = 0; i < numFields; i++)
		{
			int fieldNumber = fieldsStream.readVInt();
			FieldInfo fi = fieldInfos.getFieldInfo(fieldNumber);
			doc.add(fi.name, fieldsStream.readString());
		}

		return doc;
	}
}